package com.bac.bacplatform;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.bac.javabeans.FuellingCard;
import com.bac.utils.Config;
import com.bac.utils.Storage;
import com.bac.utils.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class ConfirmRecharge extends BaseActivity implements OnClickListener{
	
	private TextView textView2,textView4,textView6,totalTextView,ensureTextView;
	private TextView mTextviewdicount;
	private RelativeLayout rl_line1,rl_line2;
	private ImageView imageView9,imageView10;
	private Button btn_confirmpay;

	private Intent mIntent;
	
	private int mYueshu;
	
	private int mPayMethod = 2;
	
	private String mCardNo, mMoney, mCycle, mTotal;
	
	private Boolean mIsReady = false;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recharge_now);
		imageView9 = (ImageView) findViewById(R.id.imageView9);
		imageView10 = (ImageView) findViewById(R.id.imageView10);
		btn_confirmpay = (Button) findViewById(R.id.btn_confirmpay);
		mTextviewdicount = (TextView) findViewById(R.id.money_youhui);
		
		
		rl_line1 = (RelativeLayout) findViewById(R.id.rl_line1);
		rl_line1.setOnClickListener(this);
		rl_line2 = (RelativeLayout) findViewById(R.id.rl_line2);
		rl_line2.setOnClickListener(this);
		
		if (!Config.UserGeneralInfo.wealthAccountBanding) {
			Log.i("wealthAccountBanding", ""+Config.UserGeneralInfo.wealthAccountBanding);
			rl_line1.setBackgroundColor(0xFFD3D3D3);
			rl_line1.setClickable(false);
		}

		findViewById(R.id.title_left).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finishActivityOut();
			}
		});
		
		mIntent = getIntent();
		String cardName = mIntent.getStringExtra("cardNum");
		String[] cardarr = cardName.split(" ");
		mCardNo = cardarr[0];
		mCycle = mIntent.getStringExtra("monthNum");
		mMoney = mIntent.getStringExtra("money_text");
		mTotal = mIntent.getStringExtra("total");
		mPayMethod = mIntent.getIntExtra("paymethod", 2);
		Log.i("Confirm paymethond", ""+ mPayMethod);
		
	}

	@SuppressLint("NewApi")
	@Override
	public void init() {
		textView2 = (TextView) findViewById(R.id.textView2);
		textView4 = (TextView) findViewById(R.id.textView4);
		textView6 = (TextView) findViewById(R.id.textView6);
		totalTextView = (TextView) findViewById(R.id.textView8);
		ensureTextView = (TextView) findViewById(R.id.textView10);
		// 卡号，不带名字
		textView2.setText(mCardNo);
		// 金额
		textView4.setText(mMoney+".00");
		// 月数
		mYueshu = Integer.parseInt(mCycle);
		
		if (mYueshu == 1) {
			textView6.setText("立即充值");
		}else {
			textView6.setText(mYueshu+"个月");
		}
		
		if(mPayMethod == 1){
		imageView10.setImageDrawable(getResources().getDrawable(
				R.drawable.confirm_btnoff));
		imageView9.setImageDrawable(getResources().getDrawable(
				R.drawable.confirm_btnon));

		}else{
			imageView10.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnon));
			imageView9.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnoff));
		}
		btn_confirmpay.setBackground(getResources().getDrawable(
				R.drawable.btn_light));
		btn_confirmpay.setClickable(true);
		btn_confirmpay.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				checkFuellingCard(textView2.getText().toString(), mPayMethod);
			}
		});
		getDiscount();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_line1:
			mPayMethod = 1;
			choosePayWay(mPayMethod);
			break;
		case R.id.rl_line2:
			mPayMethod = 2;
			choosePayWay(mPayMethod);
			break;
		default:
			break;
		}
		
	}
	
	@SuppressLint("NewApi")
	private void choosePayWay(final int method){
		imageView9.setImageDrawable(getResources().getDrawable(
				R.drawable.confirm_btnoff));
		imageView10.setImageDrawable(getResources().getDrawable(
				R.drawable.confirm_btnoff));
		btn_confirmpay.setBackground(getResources().getDrawable(
				R.drawable.btn_grey));
		btn_confirmpay.setClickable(false);
		if (!mIsReady) {
			return;
		}
		if (method == 1) {
			imageView9.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnon));
			imageView10.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnoff));
			btn_confirmpay.setBackground(getResources().getDrawable(
					R.drawable.btn_light));
			btn_confirmpay.setClickable(true);
			
			btn_confirmpay.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					checkFuellingCard(textView2.getText().toString(), method);
				}
			});
		}else if (method == 2) {
			imageView10.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnon));
			imageView9.setImageDrawable(getResources().getDrawable(
					R.drawable.confirm_btnoff));
			btn_confirmpay.setBackground(getResources().getDrawable(
					R.drawable.btn_light));
			btn_confirmpay.setClickable(true);
			
			btn_confirmpay.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					checkFuellingCard(textView2.getText().toString(), method);
				}
			});
		}
	}
	
	public void getDiscount(){
		// 如果没有网络，就加载本地图片
				ErrorListener errorListener = new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {
						Log.i(getClass().getName(), "error");
						dismissLoadingProgress();
						showToast("请检查网络后重试");
						mIsReady = false;
					}
				};
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----getdiscount", response.toString());
				HashMap<String, String> result = new Gson().fromJson(response.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("totalRecharge")) {
					mIsReady = true;
					totalTextView.setText(result.get("totalRecharge"));
					ensureTextView.setText(result.get("actualPayment"));
					
					BigDecimal bd1 = new BigDecimal(result.get("totalRecharge"));
					BigDecimal bd2 = new BigDecimal(result.get("actualPayment"));
					BigDecimal dicount = bd1.subtract(bd2);
					if (dicount.compareTo(BigDecimal.ZERO) == 0 ) {
						mTextviewdicount.setText("没有优惠");
					}else{
						mTextviewdicount.setText("优惠"+dicount.toString());
					}
				}else {
					mIsReady = false;
				}
			}
		
		};
		
		showLoadingProgress();
		String path = Config.URL_GET_DISCOUNT;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", mTotal);
		map.put("cardNo", mCardNo);
		map.put("cycle", mCycle);
		if ("1".equals(mCycle)) {
			map.put("transactionCode", "GAS001");
		}else{
			map.put("transactionCode", "GAS004");
			map.put("cycle", mCycle);
		}
		Util.httpRequestToGetWithParams(path, sListener, errorListener, map);
	}
	
	/**
	 * 揩油宝支付
	 */
	@SuppressLint("NewApi")
	public void payForJuyoujin() {
		// 防止快速点击
		btn_confirmpay.setClickable(false);
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				btn_confirmpay.setBackground(getResources().getDrawable(
						R.drawable.btn_light));
				btn_confirmpay.setClickable(true);
				dismissLoadingProgress();
				Log.i(getClass().getName(), response.toString());

				HashMap<String, String> result = new Gson().fromJson(response,
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				if (result != null && result.containsKey("code")) {
					if (result.get("code").equals("3")) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								ConfirmRecharge.this, R.style.Custom_dialog);
						final AlertDialog alertDialog = builder.create();
						alertDialog.show();
						Window window = alertDialog.getWindow();
						View view = LayoutInflater.from(
								ConfirmRecharge.this).inflate(
								R.layout.dialog_alert, null);
						((TextView) (view.findViewById(R.id.tv_title)))
								.setText("提示");
						((TextView) (view.findViewById(R.id.tv_message)))
								.setText(result.get("errMsg"));
						view.findViewById(R.id.ly_ok).setOnClickListener(
								new OnClickListener() {
									@Override
									public void onClick(View v) {
										alertDialog.dismiss();
//										finishActivityOut();
									}
								});
						window.setContentView(view);
						window.setLayout(
								(int) (Util.getWidth(getApplicationContext()) * 0.8),
								WindowManager.LayoutParams.WRAP_CONTENT);
					} else {
						Intent intent = new Intent(ConfirmRecharge.this,
								PayResultActivityone.class);
						Bundle bundle = new Bundle();
						bundle.putString("total", totalTextView.getText().toString());
						bundle.putString("actual", ensureTextView.getText().toString());
						intent.putExtras(bundle);
						startActivityIn(intent);
					}
				}
			}
		};
		showLoadingProgress();
		String path = Config.URL_PAY_JUYOUJIN;
		Map<String, String> map = new HashMap<String, String>();
		map.put("amount", totalTextView.getText().toString());
		map.put("account", textView2.getText().toString());
		map.put("terminalId",  android.os.Build.MODEL+"/"+Util.getDeviceID(ConfirmRecharge.this));
	    map.put("transactionCode", "GAS003");
	    Log.i("pay----", "device--"+android.os.Build.MODEL+"/"+Util.getDeviceID(ConfirmRecharge.this));
		Util.httpStringPost(path, sListener, this, map);

	}

	@SuppressLint("NewApi")
	public void payForYeepay(){
		// 防止快速点击
		btn_confirmpay.setClickable(false);
		
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				btn_confirmpay.setBackground(getResources().getDrawable(
						R.drawable.btn_light));
				btn_confirmpay.setClickable(true);
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
				HashMap<String, String> result = new Gson().fromJson(response.toString().trim(),
						new TypeToken<HashMap<String, String>>() {
						}.getType());
				
				if (result != null && result.containsKey("paymentUrl")) {
					Intent intentToPay = new Intent(ConfirmRecharge.this, YeepayActivity.class);
					intentToPay.putExtra("paymentUrl", result.get("paymentUrl"));
					startActivityIn(intentToPay);
				}
			}
		};
		showLoadingProgress();
		String path = Config.URL_YEEPAY;
		
		Map<String, String> map = new HashMap<String, String>();
		String totalMoney = ""+ (mYueshu*Integer.parseInt(mMoney));
		Log.i("pay yeepay---", "amount:" + totalTextView.getText().toString());
		
		map.put("amount", totalTextView.getText().toString());
		map.put("account", mCardNo);
		map.put("terminalId", android.os.Build.MODEL+"/"+Util.getDeviceID(ConfirmRecharge.this));
	    map.put("transactionCode", "GAS001");
		Util.httpStringPost(path, sListener, this, map);
	}

	@SuppressLint("NewApi")
	@Override
	public void hanlderTimeoutError() {
		// TODO Auto-generated method stub
		super.hanlderTimeoutError();
		Log.i("ConfirmRecharge", "timeout....");
		btn_confirmpay.setClickable(true);
	}

	@SuppressLint("NewApi")
	@Override
	public void hanlderErrorShowMessage(String string) {
		// TODO Auto-generated method stub
		super.hanlderErrorShowMessage(string);
		Log.i("ConfirmRecharge", "showmessage....");
		btn_confirmpay.setClickable(true);
	}

	@SuppressLint("NewApi")
	@Override
	public void hanlderUnknowError() {
		// TODO Auto-generated method stub
		super.hanlderUnknowError();
		Log.i("ConfirmRecharge", "unknowerror....");
		btn_confirmpay.setClickable(true);
	}

	@SuppressLint("NewApi")
	@Override
	public void hanlderNetworkError() {
		// TODO Auto-generated method stub
		super.hanlderNetworkError();
		Log.i("ConfirmRecharge", "networkerror....");
		btn_confirmpay.setClickable(true);
	}
	
	/**
	 * 加油卡信息校验，对手动输入的卡号做校验
	 */
	public void checkFuellingCard(final String carNo, final int type){
		Listener<String> sListener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				dismissLoadingProgress();
				Log.i("TAG----success", response.toString());
				Gson gson = new Gson();
				FuellingCard fuellingCard = gson.fromJson(response, FuellingCard.class);
				// 计算卡号后四位
				String cardNo = fuellingCard.getCardNo();
				String card4 = cardNo.substring(cardNo.length() - 4, cardNo.length());
				final String cardOwner = fuellingCard.getCardOwner();
				String info = String.format(getString(R.string.commen_dialog_message4), card4, fuellingCard.getCardOwner());
				
					AlertDialog.Builder builder = new AlertDialog.Builder(ConfirmRecharge.this, R.style.Custom_dialog);
					final AlertDialog alertDialog = builder.create();
					alertDialog.setCanceledOnTouchOutside(false);
					alertDialog.show();
					Window window = alertDialog.getWindow();
					View view = LayoutInflater.from(ConfirmRecharge.this).inflate(R.layout.dialog_alert, null);
					view.findViewById(R.id.ly_cancel).setVisibility(View.VISIBLE);
					view.findViewById(R.id.line).setVisibility(View.VISIBLE);
					
					((TextView)(view.findViewById(R.id.tv_title))).setText(getString(R.string.commen_dialog_title1));
					((TextView)(view.findViewById(R.id.tv_message))).setText(Html.fromHtml(info));
					
					view.findViewById(R.id.ly_cancel).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
						}
					});
					
					view.findViewById(R.id.ly_ok).setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							alertDialog.dismiss();
							String username = Storage.getString(getApplicationContext(),
									Config.USER_ACCOUNT_KEY);
							if(username.length()!=0){
								Storage.saveString(getApplicationContext(), username, textView2.getText().toString());
							}
							
							Listener<String> listener = new Listener<String>() {
								@Override
								public void onResponse(String response) {
									Log.i("ConfirmRecharg check card", response);
									if (type == 1) {
										payForJuyoujin();
									}else if(type == 2){
										payForYeepay();
									}
								}
							};
							String savePath = Config.URL_SAVE_CARD;
							Map<String, String> parame = new HashMap<String, String>();
							parame.put("cardNo", carNo);
							parame.put("userName", cardOwner);
							Util.httpStringPost(savePath, listener,
									ConfirmRecharge.this, parame);
						}
					});
					window.setContentView(view);
					window.setLayout((int)(Util.getWidth(getApplicationContext()) * 0.8), WindowManager.LayoutParams.WRAP_CONTENT);
					
			}
		};
		showLoadingProgress();
		String path = Config.URL_CHECK_CARD;
		Map<String, String> map = new HashMap<String, String>();
		map.put("cardNo", carNo);
		map.put("terminalId", android.os.Build.MODEL+"/"+Util.getDeviceID(ConfirmRecharge.this));
		Util.httpStringPost(path, sListener, this, map);
	}
	
	
}
